import { fetchArticleList, ArticleResult } from '@/api/list'
import { useEffect, useState } from 'react'
import { Image, List, InfiniteScroll } from 'antd-mobile'
import { useNavigate } from 'react-router-dom'
// mock数据
// import { users } from './users'

type Props = {
    channel_id: string
}

const HomeList = (props: Props) => {

    const navigator = useNavigate()

    const { channel_id } = props

    const [articleList, setArticleList] = useState<ArticleResult>({
        results: [],
        pre_timestamp: `${new Date().getTime()}`
    })

    useEffect(() => {
        const getArticleList = async () => {
            const res = await fetchArticleList({
                channel_id: channel_id,
                timestamp: `${new Date().getTime()}`
            })
            setArticleList(res.data.data)
        }
        getArticleList()
    }, [])


    const [hasMore, setHasMore] = useState(true)
    const loadMore = async () => {
        const res = await fetchArticleList({
            channel_id,
            timestamp: articleList.pre_timestamp,
        })
        // 没有数据立刻停止
        if (res.data.data.results.length === 0) {
            setHasMore(false)
        }
        setArticleList({
            // 拼接新老列表数据
            results: [...articleList.results, ...res.data.data.results],
            // 重置时间参数 为下一次请求做准备
            pre_timestamp: res.data.data.pre_timestamp,
        })
    }

    const gotoDetail = (id: string) => navigator(`/detail?id=${id}`)

    return (
        <>
            <List>
                {articleList.results.map((item) => (
                    <List.Item
                        onClick={() => gotoDetail(item.art_id)}
                        key={item.art_id}
                        prefix={
                            <Image
                                src={item.cover.images?.[0]}
                                style={{ borderRadius: 20 }}
                                fit="cover"
                                width={40}
                                height={40}
                            />
                        }
                        description={item.pubdate}
                    >
                        {item.aut_name}
                    </List.Item>
                ))}
            </List>
            <InfiniteScroll loadMore={loadMore} hasMore={hasMore} threshold={10} />
        </>
    )
}

export default HomeList